import Vue from 'vue'
import VueI18n from 'vue-i18n'
import { getLanguage } from '@/utils/cookies'
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'
import elementJaLocale from 'element-ui/lib/locale/lang/ja'
import common from './common'
import route from './route'
import tagsView from './tagsView'
import navbar from './navbar'
import settings from '@/settings'
import login from './login'

const messages = {
  zh: { ...elementZhLocale },
  ja: { ...elementJaLocale },
  en: { ...elementEnLocale }
}
const langList = [common, route, navbar, tagsView, settings, login]
for (const lang of langList) {
  messages.zh = { ...messages.zh, ...lang.zh }
  messages.ja = { ...messages.ja, ...lang.ja }
  messages.en = { ...messages.en, ...lang.en }
}

Vue.use(VueI18n)
export const getLocale = () => {
  const cookieLanguage = getLanguage()
  if (cookieLanguage) {
    document.documentElement.lang = cookieLanguage
    return cookieLanguage
  }
  const language = navigator.language.toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      document.documentElement.lang = locale
      return locale
    }
  }
  return 'en'
}

const i18n = new VueI18n({
  locale: getLocale(),
  messages,
  silentTranslationWarn: true // 去除国际化警告
})
export default i18n
